<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class product_image extends CI_Controller{
	
	public function get_info(){
		if($this->check_session()){
			$this->load->Model("product_image_DAO");
			$imageData = $this->product_image_DAO->get($_POST['product_id']);
			echo json_encode($imageData);
		} else {
			$this->logout();
		}
	}
	
	public function add(){
		if($this->check_session()){
			$product_id = $_POST['product_id'];
			$this->load->Model("product_image_DAO");
			$this->load->Model("model/product_image_model");
			$ordinal = $_POST['ordinal'];
			$path = $_FILES['picture']['name'];
			$ext = pathinfo($path, PATHINFO_EXTENSION);
			$newName = $product_id.'_'.$ordinal.'.'.$ext;
			if (!file_exists("./images/{$product_id}/")) {
				mkdir("./images/{$product_id}/", 0777, true);
			}
			move_uploaded_file($_FILES['picture']["tmp_name"], "./images/{$product_id}/".$newName);
			$product_image_model = new product_image_model();
			$product_image_model->product_id = $product_id;
			$product_image_model->image = "./images/{$product_id}/" . $newName;
			$product_image_model->description = '';
			$product_image_model->ordinal = $_POST['ordinal'];
			$this->product_image_DAO->delete($product_id, $ordinal);
			echo $this->product_image_DAO->add($product_image_model);
		} else {
			$this->logout();
		}
	}

	public function delete(){
		if($this->check_session()){
			$this->load->Model("product_image_DAO");
			$imageData = $this->product_image_DAO->delete($_POST['product_id'], $_POST['ordinal']);
			echo json_encode($imageData);
		} else {
			$this->logout();
		}
	}
	
	public function logout(){
		$this->session->unset_userdata('session_username');
		$this->session->unset_userdata('session_role');
		redirect('/', 'refresh');
    }
	
	public function check_session(){
		$session_username = $this->session->userdata('session_username');
		return isset($session_username) && $session_username != '';
	}
}